$(function () {
    var showContentLoading = function () {
        $('.content-panel .content-panel-loading').removeClass('hidden');
    };
    var hideContentLoading = function () {
        $('.content-panel .content-panel-loading').addClass('hidden');
    };
    // 选择日期配置
    var format = 'YYYY-MM-DD';
    // 选择日期
    $('#datePickerInput').daterangepicker({
        'showDropdowns': true,
        'autoApply': true,
        'dateLimit': {
            'days': 30
        },
        'locale': {
            'format': format,
            'applyLabel': lang('date.ensure'),
            'cancelLabel': lang('date.cancel'),
            'daysOfWeek': [
                lang('week.7'),
                lang('week.1'),
                lang('week.2'),
                lang('week.3'),
                lang('week.4'),
                lang('week.5'),
                lang('week.6')
            ],
            'monthNames': [
                lang('month.1'),
                lang('month.2'),
                lang('month.3'),
                lang('month.4'),
                lang('month.5'),
                lang('month.6'),
                lang('month.7'),
                lang('month.8'),
                lang('month.9'),
                lang('month.10'),
                lang('month.11'),
                lang('month.12')
            ],
            'firstDay': 1
        },
        'linkedCalendars': false,
        'parentEl': 'body',
        'startDate': $('#datePicker').find('.start').html(),
        'endDate': $('#datePicker').find('.end').html(),
        'minDate': '2000-01-01',
        'maxDate': '2038-01-01',
        'opens': 'left'
    }, function (start, end, label) {
        $('#datePicker').find('.start').html(start.format(format));
        $('#datePicker').find('.end').html(end.format(format));
        refreshPage();
    });
    $('#datePickerContainer').on('click', function () {
        $('#datePickerInput').trigger('focus');
    });
    // 饼图配置
    var pieChartConfig = {
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie'
        },
        title: {
            text: ''
        },
        tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        credits: {
            enabled: false
        },
        plotOptions: {
            pie: {
                size: 90,
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: false
                },
                showInLegend: true
            }
        },
        legend: {
            verticalAlign: 'top',
            align: 'right',
            symbolWidth: 10,
            symbolHeight: 8,
            symbolPadding: 4,
            padding: 0,
            labelFormat: '',
            layout: 'vertical',
            backgroundColor: '#FFFFFF',
            floating: false,
            labelFormatter: function () {
//              if (textSize(12, this.name).width > 150) {
//                  return this.name.split(': ')[1];
//              }
                return this.name;
            },
            borderWidth: 0
        },
        series: [{
            name: lang('proportion'),
            colorByPoint: true,
            data: []
        }]
    };
    // 柱状图配置
    var columnChartConfig = {
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'column'
        },
        title: {
            text: ''
        },
        credits: {
            enabled: false
        },
        xAxis: {
            visible: false
        },
        yAxis: {
            title: {
                text: lang('unit.left')+window.symbols+lang('unit.right')
            },
            visible: false
        },
        tooltip: {
            formatter: function () {
                return this.series.name;
            }
        },
        legend: {
            verticalAlign: 'top',
            align: 'right',
            symbolWidth: 10,
            symbolHeight: 8,
            symbolPadding: 4,
            padding: 0,
            labelFormat: '',
            layout: 'vertical',
            backgroundColor: '#FFFFFF',
            floating: false,
            labelFormatter: function () {
//              if (textSize(12, this.name).width > 150) {
//                  return this.name.split(': ')[1];
//              }
                return this.name;
            },
            borderWidth: 0
        },
        series: []
    };
    // 数据转换柱状图
    var transformColumnChartData = function (series) {
        columnChartConfig.series = [];
        $.each(series, function (index, data) {
            columnChartConfig.series.push({
                name: data.name + ': ' + window.symbols + data.value,
                data: [parseFloat(data.value)]
            });
        });
        return columnChartConfig;
    };
    // 数据转换饼图
    var transformChartData = function (series) {
        pieChartConfig.series[0].data = [];
        $.each(series, function (index, data) {
            pieChartConfig.series[0].data.push({
                name: data.name + ': '+ window.symbols + data.total,
                y: parseFloat(data.value)
            });
        });
        return pieChartConfig;
    };
    var refreshPage = function () {
        var startDate = $('#datePicker').find('.start').html();
        var endDate = $('#datePicker').find('.end').html();
        var param = {};
        param.hotel = window.currentHotel;
        param.start = startDate;
        param.end = endDate;
        showContentLoading();
        ajaxRequest('/Home/Report/getFinance', param, 'post', function (data) {
            var info = data.data;
            // 总结余支付方式占比
            var surplusSeries = info.surplusSeries;
            // 收入支付方式占比
            var incomeSeries = info.incomeSeries;
            // 支出支付方式占比
            var outcomeSeries = info.outcomeSeries;
            // 订单明细
            var orderInfos = info.orders;
            var total = info.total;
            var pages = info.pages;
            var currentPage = 1;
            // 财务收支
            var financeOverview = $('#statisticOverview');
            financeOverview.find('span[data-tag="surplus"]').html(info.surplus);
            financeOverview.find('span[data-tag="income"]').html(info.income);
            financeOverview.find('span[data-tag="income-receipt"]').html(info.incomeReceipt);
            financeOverview.find('span[data-tag="income-deposit"]').html(info.incomeDeposit);
            financeOverview.find('span[data-tag="outcome"]').html(info.outcome);
            financeOverview.find('span[data-tag="outcome-refund"]').html(info.outcomeRefund);
            financeOverview.find('span[data-tag="outcome-deposit"]').html(info.outcomeDeposit);
            // 饼图
            $('#surplusChart').highcharts(transformColumnChartData(surplusSeries));
            $('#incomeChart').highcharts(transformChartData(incomeSeries));
            $('#outcomeChart').highcharts(transformChartData(outcomeSeries));
            // 表格渲染
            refreshTable(orderInfos);
            refreshPageFooter(currentPage, pages, total);
            $('#orderInfoContaienr>.content-panel-header').find('a').attr('href', '/Home/Report/exportPay?hotel=' + window.currentHotel + '&start=' + $('#datePicker').find('.start').html() + '&end=' + $('#datePicker').find('.end').html());
            hideContentLoading();
        }, function (error) {
            if (error.responseJSON !== undefined) {
                modalAlert(error.responseJSON.info);
            }
        });
    };
    var refreshTable = function (orderInfos) {
        var trs = '';
        var templateOriginal = $('#templateOrderPayRecord');
        $.each(orderInfos, function (index, info) {
            var template = $(templateOriginal.clone().html());
            template.find('[data-tag="date"]').html(info.date);
            template.find('[data-tag="name"]').html(info.name);
            template.find('[data-tag="remark"]').html(info.remark);
            template.find('[data-tag="from"]').html(info.from);
            template.find('[data-tag="by"]').html(info.by);
            template.find('[data-tag="type"]').html(info.type);
            template.find('[data-tag="total"]').html(info.total);
            trs += template.prop('outerHTML');
        });
        $('#orderInfoTbody').html(trs);
    };
    var refreshPageFooter = function (currentPage, pages, total) {
        currentPage = parseInt(currentPage);
        pages = parseInt(pages);
        total = parseInt(total);
        var pageItems = '';
        for (var i = 1; i <= pages; i++) {
            if (i === currentPage) {
                pageItems += '<li class="active"><a href="javascript:void(0);" data-value="' + i + '">' + i + '</a></li>';
            } else {
                pageItems += '<li><a href="javascript:void(0);" data-value="' + i + '">' + i + '</a></li>';
            }
        }
        $('#orderInfoContaienr').find('.pagination').html(pageItems);
        $('#orderInfoContaienr').find('.content-panel-pagination-count').html(total);
    };
    refreshPage();
    // 点击分页地址
    $('#orderInfoContaienr .pagination').on('click', 'li:not(.active)>a', function (e) {
        e.preventDefault();
        var pageLink = $(this);
        var param = {};
        param.hotel = window.currentHotel;
        param.current = pageLink.data('value');
        param.start = $('#datePicker').find('.start').html();
        param.end = $('#datePicker').find('.end').html();
        $('#orderInfoContaienr .content-panel-loading').removeClass('hidden');
        ajaxRequest('/Home/Report/getFinanceOrder', param, 'post', function (data) {
            var info = data.data;
            // 订单明细
            var orderInfos = info.orders;
            var total = info.total;
            var pages = info.pages;
            var currentPage = info.currentPage;
            // 表格渲染
            refreshTable(orderInfos);
            refreshPageFooter(currentPage, pages, total);
            $('#orderInfoContaienr .content-panel-loading').addClass('hidden');
        }, function (error) {
            if (error.responseJSON !== undefined) {
                modalAlert(error.responseJSON.info);
            }
        });
    });
});
